#include "widget.h"
#include "ui_widget.h"
#include <QThread>
#include <QDebug>
#include "mythread.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    myTimer = new QTimer(this);
    connect(myTimer, &QTimer::timeout, this, &Widget::dealTimeout);
    //分配空间
    thread = new myThread(this);
    connect(thread, &myThread::isDone, this, &Widget::dealDone);
    //线程用完要及时关闭
    connect(this, &Widget::destroy, this, &Widget::stopThread);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::dealTimeout()
{
    static int i = 0;
    i++;
    ui->lcdNumber->display(i);
}

void Widget::dealDone()
{
    qDebug() << "deal it over.";
    if(true == myTimer->isActive()){
        myTimer->stop();
    }
}

void Widget::stopThread()
{
    if(thread->isRunning() == false)//如果已经关闭则无需再关闭了
    {
        return;
    }
    //不要用terminate它会直接关闭导致问题,用quit关闭线程
    thread->quit();
    //等待线程处理完手头工作
    thread->wait();
}


void Widget::on_pBtnStart_clicked()
{
    if(myTimer->isActive() == false){
        myTimer->start();
    }
    //启动线程，处理数据
    thread->start();
}


void Widget::on_pBtnStop_clicked()
{
    if(true == myTimer->isActive()){
        myTimer->stop();
    }
}

